package com.leyou.order.task;

import com.leyou.order.client.AuthClient;
import com.leyou.order.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @package com.leyou.gateway.task
 * @description: 开启定时任务，定时刷新服务token
 * @author: 许超越
 * @date 2019/7/9 19:43
 * @version: V1.0
 */
@Slf4j
@Component
public class PrivilegeTokenHolder {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private AuthClient authClient;

    private String token;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;

    /**
     * 项目在启动时会先执行一次
     * @throws InterruptedException
     */
    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadToken() throws InterruptedException {
        while (true) {
            try {
                //调用ly-auth微服务获取token
                this.token = authClient.authorize(prop.getAppTokenProperties().getId(), prop.getAppTokenProperties().getSecret());
                //成功获取
                log.info("【订单服务】定时获取token成功");
                break;
            } catch (Exception e) {
                log.info("【订单服务】定时获取token失败");
            }
            //失败后隔段时间在重试
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }

    //向外提供一个get方法
    public String getToken()     {
        return token;
    }
}
